<?php
/**
 * 邮件处理工具类
 * Created by PhpStorm.
 * User: zhongbaitong
 * Date: 2020/5/21
 * Time: 22:30
 */

namespace app\service;

use sys\Controller;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use sys\Singleton;

require VENDOR_PATH . 'phpmailer/phpmailer/src/Exception.php';
require VENDOR_PATH . 'phpmailer/phpmailer/src/PHPMailer.php';
require VENDOR_PATH . 'phpmailer/phpmailer/src/SMTP.php';

class Emailer extends Controller
{
    // 单例模式类的复用
    use Singleton;
    // PHPMailer 实例
    protected $mail;

    public function __construct()
    {
        try {
            // Passing `true` enables exceptions
            $mail = new PHPMailer(true);
            $mail->isSMTP();
            //设定邮件编码
            $mail->CharSet = "UTF-8";
            // 调试模式输出
            $mail->SMTPDebug = 0;
            // 使用SMTP
            $mail->isSMTP();
            // SMTP服务器
            $mail->Host = 'smtp.qq.com';
            // 允许 SMTP 认证
            $mail->SMTPAuth = true;
            // SMTP 用户名  即邮箱的用户名
            $mail->Username = config("mail.username");
            // SMTP 密码  (邮箱开启POP3/SMTP服务时获取)
            $mail->Password = config("mail.password");
            // 允许 TLS 或者ssl协议
            $mail->SMTPSecure = 'ssl';
            // 服务器端口 25 或者465 具体要看邮箱服务器支持
            $mail->Port = 465;
            // 发件人
            $mail->setFrom(config("mail.username"), config("mail.nickname"));
            //回复的时候回复给哪个邮箱 建议和发件人一致
            $mail->addReplyTo(config("mail.username"), config("mail.nickname"));
            //$mail->addCC('cc@example.com');                    //抄送
            //$mail->addBCC('bcc@example.com');                    //密送

            //发送附件
            // $mail->addAttachment('../xy.zip');         // 添加附件
            // $mail->addAttachment('../thumb-1.jpg', 'new.jpg');    // 发送附件并且重命名

            //Content
            $this->mail = $mail;
        } catch (Exception $e) {
            echo '初始化邮件配置错误: ', $mail->ErrorInfo;
        }
    }

    /**
     * 发送邮件
     * @param array $info
     * @return bool
     */
    public function send($info = [])
    {

        $necessary = ["obj_email", "obj_username", "title", "content"];
        if (!$rs = array_diff($necessary, $info)) {
            return "lack of params: " . implode("、", $rs);
        }

        //服务器配置
        try {
            $this->mail->addAddress($info["obj_email"], $info["obj_username"]);
            // 可添加多个收件人
//            $this->mail->addAddress('946047296@qq.com', $info["obj_email"]);

            $this->mail->Subject = $info['title'];
            $this->mail->Body = $info["content"];
            $this->mail->AltBody = 'sorry,something is wrong..';

            $this->mail->send();
            return "ok";
        } catch (Exception $e) {
            return '邮件发送失败: '. $this->mail->ErrorInfo;
        }
    }

}